/**
 * <pre>
 * Title: 		SecureCommonsClientHttpRequestFactory.java
 * Project: 	Common-Util
 * Author:		linriqing
 * Create:	 	2013-10-24 上午10:03:01
 * Copyright: 	Copyright (c) 2013
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.common.web.rest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.springframework.http.client.CommonsClientHttpRequestFactory;

/**
 * <pre>
 * 基于HttpClient的SpringSecurity客户端安全认证请求工厂
 * </pre>
 * @author linriqing
 * @version 1.0, 2013-10-24
 */
public class SecureCommonsClientHttpRequestFactory extends CommonsClientHttpRequestFactory
{
	protected CredentialsProvider credentialsProvider;

	public SecureCommonsClientHttpRequestFactory(int defaultMaxConnectionsPerHost, int maxTotalConnections,
			int connTimeout, int readTimeout)
	{
		HttpConnectionManagerParams param = new HttpConnectionManagerParams();
		// 每个主机的最大并行链接数
		param.setDefaultMaxConnectionsPerHost(defaultMaxConnectionsPerHost);
		// 客户端总并行链接最大数
		param.setMaxTotalConnections(maxTotalConnections);
		// 设置连接超时时间(单位毫秒)
		param.setConnectionTimeout(connTimeout);
		// 设置读数据超时时间(单位毫秒)
		param.setSoTimeout(readTimeout);
		MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
		manager.setParams(param);
		HttpClient httpClient = new HttpClient(manager);
		super.setHttpClient(httpClient);
	}

	public CredentialsProvider getCredentialsProvider()
	{
		return credentialsProvider;
	}

	public void setCredentialsProvider(CredentialsProvider credentialsProvider)
	{
		this.credentialsProvider = credentialsProvider;
		Credentials cred = credentialsProvider.getCredentials(null);
		UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(cred.getUserName(),
				cred.getPassword());
		getHttpClient().getState().setCredentials(AuthScope.ANY, defaultcreds);
	}
}
